import axios from 'axios'
import store from '@/store'
import router from 'uni-crazy-router'

// 创建axios实例
const service = axios.create({
  baseURL: 'http://127.0.0.1:8000/uniapp', // 替换为实际API域名
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})

// 请求参数映射函数
const mapRequestFields = (data) => {
  if (!data) return data
  
  // 如果是数组，递归处理每个元素
  if (Array.isArray(data)) {
    return data.map(item => mapRequestFields(item))
  }
  
  // 如果是对象，处理字段映射
  if (typeof data === 'object') {
    const mapped = {}
    
    for (const [key, value] of Object.entries(data)) {
      let newKey = key
      let newValue = value
      
      // 字段名映射规则 - 前端参数名 -> 后端参数名
      switch (key) {
        case 'pageSize':
          newKey = 'page_size'
          break
        case 'categoryId':
          newKey = 'category_id'
          break
        case 'goodsId':
          newKey = 'goods_id'
          break
        case 'specId':
          newKey = 'spec_id'
          break
        case 'orderId':
          newKey = 'order_id'
          break
        case 'addressId':
          newKey = 'address_id'
          break
        case 'userId':
          newKey = 'user_id'
          break
        case 'createTime':
          newKey = 'create_time'
          break
        case 'updateTime':
          newKey = 'update_time'
          break
        case 'goodsName':
          newKey = 'goods_name'
          break
        case 'specName':
          newKey = 'spec_name'
          break
        case 'retailPrice':
          newKey = 'retail_price'
          break
        case 'marketPrice':
          newKey = 'market_price'
          break
        case 'salesQuantity':
          newKey = 'sales_quantity'
          break
        case 'isDefault':
          newKey = 'is_default'
          break
        case 'receiverName':
          newKey = 'receiver_name'
          break
        case 'receiverPhone':
          newKey = 'receiver_phone'
          break
        case 'detailAddress':
          newKey = 'detail_address'
          break
        case 'postalCode':
          newKey = 'postal_code'
          break
        case 'addressTag':
          newKey = 'address_tag'
          break
        case 'paymentMethod':
          newKey = 'payment_method'
          break
        case 'shippingFee':
          newKey = 'shipping_fee'
          break
        case 'discountAmount':
          newKey = 'discount_amount'
          break
        case 'totalAmount':
          newKey = 'total_amount'
          break
        case 'finalAmount':
          newKey = 'final_amount'
          break
        case 'orderStatus':
          newKey = 'order_status'
          break
        case 'paymentStatus':
          newKey = 'payment_status'
          break
        case 'tradeNo':
          newKey = 'trade_no'
          break
        case 'customerName':
          newKey = 'customer_name'
          break
        case 'customerAvatar':
          newKey = 'customer_avatar'
          break
        case 'commentId':
          newKey = 'comment_id'
          break
        case 'replyContent':
          newKey = 'reply_content'
          break
        case 'brandName':
          newKey = 'brand_name'
          break
        case 'className':
          newKey = 'class_name'
          break
        case 'shortName':
          newKey = 'short_name'
          break
        case 'imgUrl':
          newKey = 'img_url'
          break
        case 'specBarcode':
          newKey = 'spec_barcode'
          break
        case 'originalPrice':
          newKey = 'original_price'
          break
        default:
          // 如果值也是对象或数组，递归处理
          if (typeof value === 'object' && value !== null) {
            newValue = mapRequestFields(value)
          }
      }
      
      mapped[newKey] = newValue
    }
    
    return mapped
  }
  
  return data
}

// 响应字段映射函数
const mapResponseFields = (data) => {
  if (!data) return data
  
  // 如果是数组，递归处理每个元素
  if (Array.isArray(data)) {
    return data.map(item => mapResponseFields(item))
  }
  
  // 如果是对象，处理字段映射
  if (typeof data === 'object') {
    const mapped = {}
    
    for (const [key, value] of Object.entries(data)) {
      let newKey = key
      let newValue = value
      
      // 字段名映射规则 - 后端字段名 -> 前端字段名
      switch (key) {
        case 'page_size':
          newKey = 'pageSize'
          break
        case 'category_id':
          newKey = 'categoryId'
          break
        case 'goods_id':
          newKey = 'goodsId'
          break
        case 'spec_id':
          newKey = 'specId'
          break
        case 'order_id':
          newKey = 'orderId'
          break
        case 'address_id':
          newKey = 'addressId'
          break
        case 'user_id':
          newKey = 'userId'
          break
        case 'create_time':
          newKey = 'createTime'
          break
        case 'update_time':
          newKey = 'updateTime'
          break
        case 'goods_name':
          newKey = 'goodsName'
          break
        case 'spec_name':
          newKey = 'specName'
          break
        case 'retail_price':
          newKey = 'retailPrice'
          break
        case 'market_price':
          newKey = 'marketPrice'
          break
        case 'sales_quantity':
          newKey = 'salesQuantity'
          break
        case 'is_default':
          newKey = 'isDefault'
          break
        case 'receiver_name':
          newKey = 'receiverName'
          break
        case 'receiver_phone':
          newKey = 'receiverPhone'
          break
        case 'detail_address':
          newKey = 'detailAddress'
          break
        case 'postal_code':
          newKey = 'postalCode'
          break
        case 'address_tag':
          newKey = 'addressTag'
          break
        case 'payment_method':
          newKey = 'paymentMethod'
          break
        case 'shipping_fee':
          newKey = 'shippingFee'
          break
        case 'discount_amount':
          newKey = 'discountAmount'
          break
        case 'total_amount':
          newKey = 'totalAmount'
          break
        case 'final_amount':
          newKey = 'finalAmount'
          break
        case 'order_status':
          newKey = 'orderStatus'
          break
        case 'payment_status':
          newKey = 'paymentStatus'
          break
        case 'trade_no':
          newKey = 'tradeNo'
          break
        case 'customer_name':
          newKey = 'customerName'
          break
        case 'customer_avatar':
          newKey = 'customerAvatar'
          break
        case 'comment_id':
          newKey = 'commentId'
          break
        case 'reply_content':
          newKey = 'replyContent'
          break
        case 'brand_name':
          newKey = 'brandName'
          break
        case 'class_name':
          newKey = 'className'
          break
        case 'short_name':
          newKey = 'shortName'
          break
        case 'img_url':
          newKey = 'imgUrl'
          break
        case 'spec_barcode':
          newKey = 'specBarcode'
          break
        case 'original_price':
          newKey = 'originalPrice'
          break
        default:
          // 如果值也是对象或数组，递归处理
          if (typeof value === 'object' && value !== null) {
            newValue = mapResponseFields(value)
          }
      }
      
      mapped[newKey] = newValue
    }
    
    return mapped
  }
  
  return data
}

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加token
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    
    // 参数名映射
    if (config.data) {
      config.data = mapRequestFields(config.data)
    }
    if (config.params) {
      config.params = mapRequestFields(config.params)
    }
    
    // 添加时间戳参数，防止缓存
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        _t: Date.now()
      }
    }
    
    return config
  },
  error => {
    // console.log('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { data } = response
    
    // 字段名映射
    const mappedData = mapResponseFields(data)
    
    // 根据业务状态码处理响应
    if (mappedData.code !== 200) {
      uni.showToast({
        title: mappedData.message || '请求失败',
        icon: 'none'
      })
      
      // 401:未登录或token过期
      if (mappedData.code === 401) {
        store.dispatch('user/logout')
        router.push({ name: 'Login' })
      }
      
      return Promise.reject(new Error(mappedData.message || '请求失败'))
    } else {
      return mappedData
    }
  },
  error => {
    // console.log('响应错误:', error)
    
    let message = '网络错误，请稍后再试'
    if (error.response) {
      const status = error.response.status
      switch (status) {
        case 400:
          message = '参数错误'
          break
        case 403:
          message = '权限不足'
          break
        case 404:
          message = '请求资源不存在'
          break
        case 500:
          message = '服务器内部错误'
          break
      }
    }
    
    uni.showToast({
      title: message,
      icon: 'none'
    })
    
    return Promise.reject(error)
  }
)

// 封装请求方法
const http = {
  get(url, params = {}) {
    return service.get(url, { params })
  },
  
  post(url, data = {}) {
    return service.post(url, data)
  },
  
  put(url, data = {}) {
    return service.put(url, data)
  },
  
  delete(url, params = {}) {
    return service.delete(url, { params })
  },
  
  upload(url, file, params = {}) {
    const formData = new FormData()
    formData.append('file', file)
    
    Object.keys(params).forEach(key => {
      formData.append(key, params[key])
    })
    
    return service.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

export default http    